package area

import (
	"system-admin/config/mysql"
	"system-admin/internal/models"

	"192.168.1.75/go-pkg/helper"
)

// AllTree 区域树状列表
func AllTree(maxLevel int) ([]map[string]interface{}, error) {
	if maxLevel <= 0 || maxLevel >= 4 {
		maxLevel = 3
	}
	// 获取记录
	var areas []struct {
		ID       string `json:"id" gorm:"column:id;primaryKey;type:int;size:64;comment:主键id"`
		Name     string `json:"name" gorm:"column:name;type:string;size:40;comment:名称"`
		ParentID string `json:"parent_id" gorm:"column:parent_id;type:int;size:64;comment:父级id"`
	}
	mysql.NewDB().Model(&models.Area{}).
		Select("id", "name", "parent_id").
		Where("level <= ?", maxLevel).
		Find(&areas)

	// 转成树结构
	t := helper.NewTree("ID", "ParentID")
	return t.ListToTree("0", areas)
}
